package com.henu.cee_service.service.impl;

import com.github.pagehelper.PageHelper;
import com.henu.cee_service.entity.News;
import com.henu.cee_service.exception.BusinessException;
import com.henu.cee_service.exception.code.BaseResponseCode;
import com.henu.cee_service.mapper.NewsMapper;
import com.henu.cee_service.service.NewsService;
import com.henu.cee_service.service.RedisService;
import com.henu.cee_service.utils.PageUtil;
import com.henu.cee_service.vo.req.NewsAddReqVO;
import com.henu.cee_service.vo.req.NewsPageReqVO;
import com.henu.cee_service.vo.req.NewsUpdateReqVO;
import com.henu.cee_service.vo.resq.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * description: NewsServiceImpl
 * date: 2020/9/19 16:53
 * author: JSM
 * version: 1.0
 */

@Service
@Slf4j
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public PageVO<News> pageInfo(NewsPageReqVO vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<News> list = newsMapper.selectAll(vo);
//        for (int i = 0; i < list.size(); i++) {
//            News news = list.get(i);
//            System.out.println(news.getContent());
//        }
        return PageUtil.getPageVO(list);
    }

    @Override
    public void addNew(NewsAddReqVO vo) {
        News news = new News();
        BeanUtils.copyProperties(vo, news);
        news.setReleaseTime(new Date());
        news.setPageView(0);
        int count = newsMapper.insertSelective(news);
        if (count != 1) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }

    @Override
    public News queryById(Integer id) {
        News news = newsMapper.selectByPrimaryKey(id);
        news.setPageView(news.getPageView()+1);
        newsMapper.updatePageView(news);
        return news;
    }

    @Override
    public void updateNew(NewsUpdateReqVO vo) {
        News news = newsMapper.selectByPrimaryKey(vo.getId());
        if (null == news) {
            log.error("传入id:{} 不合法",vo.getId());
            throw new BusinessException(BaseResponseCode.DATA_ERROR);
        }
        BeanUtils.copyProperties(vo, news);
        news.setReleaseTime(new Date());
        int count = newsMapper.updateByPrimaryKeySelective(news);
        if (1 != count) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }

    @Override
    public void deleteNew(Integer id) {
        newsMapper.deleteByPrimaryKey(id);
    }
}
